package dal

import (
	"context"
	"fmt"

	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"

	"gorm.io/gorm"
)

// Get procure storage instance
func GetProcureDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.Procure))
}

// 我要买
type Procure struct {
	DB *gorm.DB
}

// Query procures from the database based on the provided parameters and options.
func (a *Procure) Query(ctx context.Context, params schema.ProcureQueryParam, opts ...schema.ProcureQueryOptions) (*schema.ProcureQueryAdminResult, error) {
	var opt schema.ProcureQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}
	db := a.DB.Table(fmt.Sprintf("%s AS p", new(schema.Procure).TableName())).
		Joins(fmt.Sprintf("left join %s m on m.uid = p.w_id", new(schema.Staff).TableName())).
		Select("p.*,m.name as staff_name,m.phone as staff_phone")

	if v := params.Status; len(v) > 0 {
		db = db.Where("status = ?", v)
	}

	if params.Source == 1 {
		db = db.Where("uid = ?", params.WID)
	} else if params.Source == 2 {
		if params.Types == 1 {
			db = db.Where("types = 1") // 1发布  2已联系
		} else if params.Types == 2 {
			db = db.Where("w_id = ?", params.WID).Where("types = 2")
		}
	} else if params.Source == 3 { // 管理员 所查看的
		if params.Types == 1 {
			db = db.Where("types = 1") // 1发布  2已联系
		} else if params.Types == 2 {
			db = db.Where("types = 2")
		}
	}

	var list schema.ProcureAdmins
	pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	queryResult := &schema.ProcureQueryAdminResult{
		PageResult: pageResult,
		Data:       list,
	}
	return queryResult, nil
} // Query procures from the database based on the provided parameters and options.
func (a *Procure) QueryAdmin(ctx context.Context, params schema.ProcureQueryParam, opts ...schema.ProcureQueryOptions) (*schema.ProcureQueryAdminResult, error) {
	var opt schema.ProcureQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := a.DB.Table(fmt.Sprintf("%s AS p", new(schema.Procure).TableName())).
		Joins(fmt.Sprintf("left join %s m on m.uid = p.w_id", new(schema.Staff).TableName())).
		Select("p.*,m.name as staff_name,m.phone as staff_phone")

	if v := params.LikeName; len(v) > 0 {
		db = db.Where("p.name LIKE ?", "%"+v+"%")
	}
	if v := params.LikeUserName; len(v) > 0 {
		db = db.Where("p.user_name LIKE ?", "%"+v+"%")
	}

	var list schema.ProcureAdmins
	pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	queryResult := &schema.ProcureQueryAdminResult{
		PageResult: pageResult,
		Data:       list,
	}
	return queryResult, nil
}

// Get the specified procure from the database.
func (a *Procure) Get(ctx context.Context, id string, opts ...schema.ProcureQueryOptions) (*schema.Procure, error) {
	var opt schema.ProcureQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	item := new(schema.Procure)
	ok, err := util.FindOne(ctx, GetProcureDB(ctx, a.DB).Where("id=?", id), opt.QueryOptions, item)
	if err != nil {
		return nil, errors.WithStack(err)
	} else if !ok {
		return nil, nil
	}
	return item, nil
}

// Exist checks if the specified procure exists in the database.
func (a *Procure) Exists(ctx context.Context, id string) (bool, error) {
	ok, err := util.Exists(ctx, GetProcureDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

// Create a new procure.
func (a *Procure) Create(ctx context.Context, item *schema.Procure) error {
	result := GetProcureDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

// Update the specified procure in the database.
func (a *Procure) Update(ctx context.Context, item *schema.Procure) error {
	result := GetProcureDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

// Update the specified procure in the database.
func (a *Procure) UpdateContact(ctx context.Context, item *schema.Procure) error {
	result := GetProcureDB(ctx, a.DB).Where("id=?", item.ID).Updates(schema.Procure{
		WID:       item.WID,
		UpdatedAt: item.UpdatedAt,
		SendAt:    item.UpdatedAt,
	})
	return errors.WithStack(result.Error)
}

// Update the specified procure in the database.
func (a *Procure) UpdateContactType(ctx context.Context, item *schema.Procure) error {
	result := GetProcureDB(ctx, a.DB).Where("id=?", item.ID).Updates(schema.Procure{
		Types: 2,
		OkAt:  item.OkAt,
	})
	return errors.WithStack(result.Error)
}

// Delete the specified procure from the database.
func (a *Procure) Delete(ctx context.Context, id string) error {
	result := GetProcureDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Procure))
	return errors.WithStack(result.Error)
}
